package com.jzo2o.orders.manager.service.impl.client;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.jzo2o.api.customer.AddressBookApi;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 熔断降级服务类，用于调用jzo2o-customer服务
 */
@Component
@Slf4j
public class CustomerClient {
    @Resource
    private AddressBookApi addressBookApi;

    //value：资源名称，sentinel基于资源进行限流，熔断
    @SentinelResource(value = "getAddressBookDetail", fallback = "detailFallback", blockHandler = "detailBlockHandler")
    public AddressBookResDTO getDetail(Long id) {
        // 打印所有已加载的限流规则
        List<FlowRule> rules = FlowRuleManager.getRules();
        System.out.println("当前限流规则总数：" + rules.size());
        for (FlowRule rule : rules) {
            if ("getAddressBookDetail".equals(rule.getResource())) {
                System.out.println("匹配到目标规则：" + rule);
            }
        }
        return addressBookApi.detail(id);
    }

    //fallback：异常时候的降级处理
    public AddressBookResDTO detailFallback(Long id, Throwable throwable) {
        log.error("运行异常，id:{},throwable:", id, throwable);
        return null;
    }

    //blockHandler：触发限流/降级时候的降级处理
    public AddressBookResDTO detailBlockHandler(Long id, BlockException blockExc) {
        log.error("触发限流、熔断，id:{},throwable:", id, blockExc);
        return null;
    }

}
